import { defineStore } from 'pinia'
import { ref } from 'vue'
import { chanrole } from '../utils/changerole.ts'
import router from '../router/index.ts'
export const roleStore = defineStore('role', () => {
  const rolelist = ref({})
  const getrolelist = (data) => {
    rolelist.value = chanrole(data)
    getrouter(rolelist.value)
  }
  const getrouter = (list) => {
    list.forEach(item => {
      const rou = {
        name: item.name,
        path: item.path,
        component: `${item.name}${item.path}`,
        children: []
      }
      if (item.children && item.children.length) {
        item.children.forEach(sitem => {
          const rou2 = {
            name: sitem.name,
            path: sitem.path,
            component: `${item.name}${sitem.path}`
          }
            let path = loadpath(rou2.component)
            rou2.component = path
            rou.children.push(rou2)
        })
      }
        let path = loadpath(rou.component)
        rou.component = path
        router.addRoute('menu', rou)
    })
    function loadpath(url) {
      let Moudle = import.meta.glob("@/views/**/*.vue")
      return Moudle[`/src/views/${url}.vue`]
    }
  }
  const addrouter=()=>{
    getrouter(rolelist.value)
  }
  return { rolelist,addrouter, getrolelist }
}, {
  persist: true
})